import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/LoginTypeEnum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/view/login_page.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/provider/global_state_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

ButtonStyle customButtonStyle = ButtonStyle(
  padding: MaterialStateProperty.all<EdgeInsetsGeometry>(EdgeInsets.symmetric(vertical: 2, horizontal: 4)),
  // 其他样式属性...
);
class LoginFormModel {
  late LoginTypeEnum loginType;
  late String imei;
  late String imeiPassword;
  late String phone;
  late String phonePassword;
  late bool rememberPassword;
}

class LoginForm extends ConsumerStatefulWidget {
  LoginForm({super.key, this.callback});

  final ValueChanged<LoginFormModel>? callback;

  final loginModel = LoginFormModel();

  @override
  ConsumerState<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends ConsumerState<LoginForm> {


  final _imeiController = TextEditingController();
  final _imeiPasswordController = TextEditingController();

  final _phoneController = TextEditingController();
  final _phonePasswordController = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
  }

  _afterLayout(_) {
    // 测试设备号登录
    ref.read(globalStateProvider.notifier).updateLoginType(LoginTypeEnum.device);
    // _imeiController.text = "58053177512";
    // _imeiPasswordController.text = "123456";
    // 是否记住了密码（rememberPasswordModel仅支持记住设备登录、手机号登录的密码）
    final rememberPasswordModel = SpUtil.getObj('rememberPasswordModel', (v) => RememberPasswordModel().fromJson(v),
        defValue: RememberPasswordModel(rememberPassword: false)) as RememberPasswordModel;
    if (rememberPasswordModel.rememberPassword!) {
      if (rememberPasswordModel.loginType == '4') {
        _imeiController.text = rememberPasswordModel.username!;
        _imeiPasswordController.text = rememberPasswordModel.password!;
      } else {
        _phoneController.text = rememberPasswordModel.username!;
        _phonePasswordController.text = rememberPasswordModel.password!;
      }
    }
  }

  /// 构建登录表单输入框
  List<Widget> _buildLoginFormTextFields() {
    final loginType = ref.watch(globalStateProvider).loginType;
    final textColor = Colors.black;
    return loginType == LoginTypeEnum.device
        ? [
            // 设备号登录
            TextField(
              controller: _imeiController,
              onChanged: (str) {},
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入设备号",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                filled: true,
                fillColor: const Color(0xffffffff),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 12,
            ),
            TextField(
              controller: _imeiPasswordController,
              obscureText: true,
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入密码",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                filled: true,
                fillColor: const Color(0xffffffff),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
              ),
            ),
          ]
        : [
            // 手机号登录
            TextField(
              controller: _phoneController,
              style: TextStyle(color: textColor),
              decoration: InputDecoration(
                hintText: "请输入手机号",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                filled: true,
                fillColor: const Color(0xffffffff),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 12,
            ),
            TextField(
              controller: _phonePasswordController,
              style: TextStyle(color: textColor),
              obscureText: true,
              decoration: InputDecoration(
                hintText: "请输入密码",
                hintStyle: TextStyle(
                  fontSize: 15,
                  color: AppTheme.themeConfig.infoTextColor,
                ),
                filled: true,
                fillColor: const Color(0xffffffff),
                // 调整内边距
                contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 0.0),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(32),
                  borderSide: BorderSide(
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                ),
              ),
            ),
          ];
  }

  /// 登录按钮点击事件
  _onLoginBtnClick() {
    XLogger.debug('点击登录');
    final loginType = ref.watch(globalStateProvider).loginType;
    final rememberPassword = ref.watch(rememberPasswordProvider);
    if (loginType == LoginTypeEnum.device) {
      // 设备号登录
      final imei = _imeiController.text;
      final imeiPassword = _imeiPasswordController.text;
      if (imei.isEmpty) {
        ToastUtils.showToast("请输入设备号");
        return;
      }
      if (imeiPassword.isEmpty) {
        ToastUtils.showToast("请输入密码");
        return;
      }
      widget.loginModel.loginType = LoginTypeEnum.device;
      widget.loginModel.imei = imei;
      widget.loginModel.imeiPassword = imeiPassword;
    } else {
      // 手机号登录
      final phone = _phoneController.text;
      final phonePassword = _phonePasswordController.text;
      if (phone.isEmpty) {
        ToastUtils.showToast("请输入手机号");
        return;
      }
      if (phonePassword.isEmpty) {
        ToastUtils.showToast("请输入密码");
        return;
      }
      widget.loginModel.loginType = LoginTypeEnum.phone;
      widget.loginModel.phone = phone;
      widget.loginModel.phonePassword = phonePassword;
    }
    widget.loginModel.rememberPassword = rememberPassword;
    widget.callback?.call(widget.loginModel);
  }

  Widget _buildRemenber() {
    bool value = ref.watch(rememberPasswordProvider);

    return Container(
      width: 100,
      height: 25,
      //在此设置
      decoration: BoxDecoration(
        image: DecorationImage(
          image: value ? AssetImage("assets/images/login/remenberbutton_selected.png") : AssetImage("assets/images/login/rememberbutton.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: ElevatedButton(
        onPressed: () {
           ref.read(rememberPasswordProvider.notifier).state = !value;
        },
        child: const Text(
          '记住密码',
          style: TextStyle(fontSize: 14, color: Colors.white),
        ),
        style: ButtonStyle(
          alignment: Alignment.centerRight,
          //去除阴影
          elevation: MaterialStateProperty.all(0),
          padding: MaterialStateProperty.all<EdgeInsetsGeometry>(
          EdgeInsets.symmetric(vertical: 0, horizontal: 10)),
          //将按钮背景设置为透明
          backgroundColor: MaterialStateProperty.all(Colors.transparent),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 屏幕高
    double screenHeight = ScreenUtil.getInstance().screenHeight;
    double offset = screenHeight / 4 - 120;

    return Container(
      padding: const EdgeInsets.only(left: 60, right: 60),
      child: Transform.translate(
        // offset: Offset(0, offset),
        offset: Offset(0, 0),
        child: Column(
          // mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 输入框
            ..._buildLoginFormTextFields(),
            // 记住密码x
            SizedBox(height: 20,),

            Row(
              children: [
                // Checkbox(
                //   value: ref.watch(rememberPasswordProvider),
                //   onChanged: (value) {
                //     ref.read(rememberPasswordProvider.notifier).state = value!;
                //   },
                //   // 选中的颜色
                //   activeColor: AppTheme.themeConfig.primaryColor,
                // ),
                // const Text(
                //   "记住密码",
                //   style: TextStyle(color: Colors.white),
                // ),
                _buildRemenber(),
                const Spacer(),
                if (ref.watch(globalStateProvider).loginType == LoginTypeEnum.phone)
                  SizedBox(
                    width: 100,
                    height: 25,
                    child: TextButton(
                      onPressed: () {
                        context.push(RouterManager.forgotPassword);
                      },
                      style: TextButton.styleFrom(
                        padding: EdgeInsets.only(top: 0),
                        backgroundColor: AppTheme.themeConfig.primaryColor,
                      ),
                      child: const Text(
                        "修改密码",
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  )
              ],
            ),
            SizedBox(height: 20,),

            Container(
              width: 200,
              height: 50,
              //在此设置
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                gradient: const LinearGradient(colors: [
                  Color(0xff1FC7FF),
                  Color(0xff003ABC),
                ]),
              ),
              child: ElevatedButton(
                onPressed: () {
                  print('按钮被点击了');
                  _onLoginBtnClick();
                  // 测试绑定手机号
                  // context.pushNamed('bind-phone');
                },
                child: const Text(
                  '登录',
                  style: TextStyle(fontSize: 17, color: Colors.white),
                ),
                style: ButtonStyle(
                  //去除阴影
                  elevation: MaterialStateProperty.all(0),
                  //将按钮背景设置为透明
                  backgroundColor: MaterialStateProperty.all(Colors.transparent),
                ),
              ),
            ),
            // 登录按钮
            // Container(
            //   width:  200,
            //   height: 50,
            //   // child: ElevatedButton(
            //   //
            //   //   onPressed: () {
            //   //
            //   //     _onLoginBtnClick();
            //   //     // 测试绑定手机号
            //   //     // context.pushNamed('bind-phone');
            //   //   },
            //   //
            //   //   child: const Text(
            //   //     "登录",
            //   //     style: TextStyle(color: Colors.red),
            //   //   ),
            //   // ),
            // ),
        //     SizedBox(
        //       height: offset,
        //     )
          ],
        ),
      ),
    );
  }
}
